package com.zhiwang.planet.mvvm.viewmodel.entertain

import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableInt
import androidx.lifecycle.*
import com.iBookStar.views.YmConfig
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider
import com.zhiwang.planet.BR
import com.zhiwang.planet.R
import com.zhiwang.planet.di.ActivityScope
import com.zhiwang.planet.event.PlayAdVideoEvent
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.mvvm.model.entity.main.MiniGame
import com.zhiwang.planet.mvvm.viewmodel.ShareViewModel
import com.zhiwang.planet.mvvm.viewmodel.main.sharedViewModels
import com.zhiwang.planet.ui.main.PlayGameProxy
import com.zhiwang.planet.ui.my.MyGameListActivity
import com.zhiwang.planet.ui.my.WithdrawActivity
import com.zhiwang.planet.util.*
import me.tatarka.bindingcollectionadapter2.ItemBinding
import me.tatarka.bindingcollectionadapter2.OnItemBind
import org.greenrobot.eventbus.EventBus
import javax.inject.Inject


object EntertainConnectionViewModel : ViewModel() {

    var triggerMyGame = MutableLiveData<Boolean>()

}


@ActivityScope
class EntertainViewModel @Inject constructor(var context: AppCompatActivity, var restApi: RestApi, var lifecycleOwner: Lifecycle) : ViewModel(), LifecycleOwner {

    var playCallBack: PlayGameProxy? = null
    val TAG = "EntertainViewModel"

    var ruleMsg = ""

    val shareViewModel by sharedViewModels<ShareViewModel>()

    override fun getLifecycle(): Lifecycle {
        return lifecycleOwner
    }

    init {

        EntertainConnectionViewModel.triggerMyGame.observe(this, Observer {
            context.quickStartActivity(MyGameListActivity::class.java)
        })


    }

    /*我的游戏*/
    val myGameBinding = OnItemBind<MyGameItemViewModel> { itemBinding, position, item ->
        itemBinding.set(
                BR.myGameItemViewModel,
                if (item.more) R.layout.item_my_game_more else R.layout.item_my_mini_game)
    }
    val myGameData = MutableLiveData<List<MyGameItemViewModel?>>()


    val gamePlayedTime  = MutableLiveData<Int>()

    val gameExcuted = MutableLiveData<Boolean>()

    val gamePlayedId = MutableLiveData<String>()

    /*所有游戏*/
    val gameBinding = ItemBinding.of<GameItemViewModel>(BR.gameItemViewModel, R.layout.item_game_list)

    val currCate = MutableLiveData<List<GameItemViewModel>>()

    val categoryGameList = ArrayList<List<GameItemViewModel>>()

    val indicator0 = ObservableInt(R.drawable.withdraw_bar)

    val indicator1 = ObservableInt(0)
    val indicator2 = ObservableInt(0)
    val indicator3 = ObservableInt(0)
    val indicator4 = ObservableInt(0)


    val allIndicators = arrayListOf(indicator0, indicator1, indicator2, indicator3, indicator4)

    fun selectCategory(index: Int) {
        currCate.value = categoryGameList[index]

        allIndicators.forEachIndexed { pos, item ->
            if (pos == index) {
                allIndicators[pos].set(R.drawable.withdraw_bar)
            } else allIndicators[pos].set(0)
        }
    }

    fun start() {

        val disposable = restApi.getGame()
                .androidSchedule()
                .responseFunc()
                .autoDispose(AndroidLifecycleScopeProvider.from(lifecycleOwner))
                .subscribe({
                    ruleMsg = it.rule
                    myGameData.value = mapMyGame(it.mygame)
                    brewCategoryGame(it.allgame)
                    currCate.value = categoryGameList[0]
                    if (categoryGameList.isNotEmpty())
                        selectCategory(0)
                }, {

                }, {

                })
    }

    private fun brewCategoryGame(games: List<MiniGame>) {
        val yizhi = arrayListOf<GameItemViewModel>()
        val shot = arrayListOf<GameItemViewModel>()
        val lanren = arrayListOf<GameItemViewModel>()
        val xiuxian = arrayListOf<GameItemViewModel>()
        val all = arrayListOf<GameItemViewModel>()


        with(categoryGameList) {
            yizhi.addAll(mapAllGame(games.filter { it.tags.contains("益智") }))
            shot.addAll(mapAllGame(games.filter { it.tags.contains("射击") }))
            lanren.addAll(mapAllGame(games.filter { it.tags.contains("经营") }))
            xiuxian.addAll(mapAllGame(games.filter { it.tags.contains("休闲") }))
            all.addAll(mapAllGame(games))
            this.add(yizhi)
            this.add(shot)
            this.add(lanren)
            this.add(xiuxian)
            this.add(all)
        }

    }

    private fun mapAllGame(allgame: List<MiniGame>): List<GameItemViewModel> = allgame.map { t ->
        GameItemViewModel(t.gameid, t.gamename, t.icon, t.tags, cb = playCallBack)
    }

    private fun mapMyGame(mygame: List<MiniGame>): List<MyGameItemViewModel> {

        val list = ArrayList<MyGameItemViewModel>()

        mygame.forEach {

            list.add(MyGameItemViewModel(it.gameid, it.gamename, it.icon, it.tags, playCallBack))

        }
        list.add(MyGameItemViewModel().also { it.cb = playCallBack })
        return list


    }

    fun withdraw() {}/*context.quickStartActivity(WithdrawActivity::class.java)*/

    fun read() = YmConfig.openReader()

    fun video() = EventBus.getDefault().post(PlayAdVideoEvent)


    fun loadTodayProfit() {

        viewModelScope.launchDelayError(errHandler = ::handleError) {
            val res = restApi.loadTodayEarning()
            if (res.isOk()) {
                shareViewModel.todayEntertainProfit.value = res.data
            } else if(res.isAuthExpired()){
                shareViewModel.todayEntertainProfit.value ="0"
            }

        }
    }

    fun handleError(e: Throwable) {
        Toaster.message(e.message ?: "未知错误0")
    }
}